package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 甜圆
 * @version v1.0.1
 * @date 2025/9/2 16:34
 * @package com.sky.service.impl
 * @copyright 甜圆
 */
@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 统计指定时间区间内的营业额数据（营业额统计）
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getturnoverStatistics(LocalDate begin, LocalDate end) {
        //当前集合用于存放从begin到end的所有日期
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);
        while (!begin.equals(end)){
            //日期计算，计算指定日期的后一天对应的日期
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //存放每天的营业额数据
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //查询日期对应的营业额数据（状态为“已完成”的订单金额合计）
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);//某一天的00:00:00
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);//某一天的23:59:59

            // SELECT SUM(amount) FROM orders WHERE order_time >= beginTime AND order_time < endTime AND status = 5
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            //统计总营业额
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;//Double类型的值可能为null，所以要判断
            turnoverList.add(turnover);
        }

        String tempDateList = StringUtils.join(dateList, ",");//通过工具类把集合转为字符串
        String tempTurnoverList = StringUtils.join(turnoverList, ",");//通过工具类把集合转为字符串

        return TurnoverReportVO
                .builder()
                .dateList(tempDateList)
                .turnoverList(tempTurnoverList)
                .build();
    }

    /**
     * 统计指定时间区间内的用户数据（用户统计）
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //当前集合用于存放从begin到end的所有日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            //日期计算，计算指定日期的后一天对应的日期
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //存放每天的新增用户数量 select count(id) from user where create_time >= beginTime and create_time < endTime
        List<Integer> newUserList = new ArrayList<>();
        //存放每天的总用户数量 select count(id) from user where create_time < endTime
        List<Integer> totalUserList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //查询日期对应的用户数据
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);//00:00:00
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);//23:59:59
            Map map = new HashMap();
            map.put("end", endTime);
            //统计总用户数量
            Integer totalUser = userMapper.countByMap(map);
            totalUser = totalUser == null ? 0 : totalUser;//值可能为null，所以要判断，但是前端好像设定为0
            totalUserList.add(totalUser);
            map.put("begin", beginTime);
            //统计新增用户数量
            Integer newUser = userMapper.countByMap(map);
            newUser = newUser == null ? 0 : newUser;//值可能为null，所以要判断，但是前端好像设定为0
            newUserList.add(newUser);
        }
        return UserReportVO
                .builder().dateList(StringUtils.join(dateList, ","))//通过工具类把集合转为字符串)
                .totalUserList(StringUtils.join(totalUserList, ","))//通过工具类把集合转为字符串)
                .newUserList(StringUtils.join(newUserList, ","))//通过工具类把集合转为字符串)
                .build();
    }

    /**
     * 统计指定时间区间内的订单数据（订单统计）
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //当前集合用于存放从begin到end的所有日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            //日期计算，计算指定日期的后一天对应的日期
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //存放每天的订单数 select count(id) from orders where order_time >= beginTime and order_time < endTime
        List<Integer> orderCountList = new ArrayList<>();
        //存放每天的有效订单数 select count(id) from orders where order_time >= beginTime and order_time < endTime and status = 5
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //查询日期对应的订单数据
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);//00:00:00
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);//23:59:59
            //统计每天的订单数
            Integer orderCount = getOrderCount(beginTime, endTime, null);
            orderCount = orderCount == null ? 0 : orderCount;//值可能为null，所以要判断，但是前端好像设定为0
            orderCountList.add(orderCount);
            //统计每天的有效订单数
            Integer validOrderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);
            validOrderCount = validOrderCount == null ? 0 : validOrderCount;//值可能为null，所以要判断，但是前端好像设定为0
            validOrderCountList.add(validOrderCount);
        }
        //计算时间区间内的订单总数量
        // 其中 Integer::sum 是 方法引用，代表 “调用 Integer 类的 sum(int a, int b) 方法”—— 也就是告诉 reduce()：“合并两个元素时，用‘相加’的逻辑”。
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();//reduce方法用于合并
        //计算时间区间内的有效订单数量
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();//reduce方法用于合并
        //计算订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount !=0){
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;//转为double类型，否则结果为0
        }
        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))//通过工具类把集合转为字符串)
                .orderCountList(StringUtils.join(orderCountList, ","))//通过工具类把集合转为字符串)
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))//通过工具类把集合转为字符串)
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }
    /**
     * 根据条件统计订单数量(订单统计)
     * @param begin
     * @param end
     * @param status
     * @return
     */
    private Integer getOrderCount(LocalDateTime begin, LocalDateTime end, Integer status) {
        Map map = new HashMap();
        map.put("begin", begin);
        map.put("end", end);
        map.put("status", status);
        return orderMapper.countByMap(map);
    }

    /**
     * 统计指定时间区间内的订单数据(获取销量排名top10)
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        //查询日期对应的销量数据
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);//00:00:00
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);//23:59:59
        List<GoodsSalesDTO> goodsSalesDTOS = orderMapper.getSalesTop10(beginTime, endTime);

        //通过stream流，将goodsSalesDTOS集合中的name属性取出来，组成一个新的集合
        List<String> names = goodsSalesDTOS.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameList = StringUtils.join(names, ",");//通过工具类把集合转为字符串
        //通过stream流，将goodsSalesDTOS集合中的number属性取出来，组成一个新的集合
        List<Integer> numbers = goodsSalesDTOS.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberList = StringUtils.join(numbers, ",");//通过工具类把集合转为字符串

        return SalesTop10ReportVO
                .builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /**
     * 导出运营数据Excel报表
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //1.查询数据库，获取营业数据--查询最近30的运营数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);//获取当前时间减去30天
        LocalDateTime begin = LocalDateTime.of(dateBegin, LocalTime.MIN);//00:00:00
        LocalDate dateEnd = LocalDate.now().minusDays(1);///获取当前时间减去1天
        LocalDateTime end = LocalDateTime.of(dateEnd, LocalTime.MAX);//23:59:59
        //查询概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(begin, end);
        //2.通过POI将营业数据写入到Excel中
        //获得类对象.再获得类加载器.通过类加载器从类路径下读取资源，最终返回输入流对象（相当于读操作）
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        //基于模板文件创建一个新的Excel文件
        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);//读
            //获取表格文件的Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");//读
            //填充数据--时间（先读后写）
            sheet.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);
            //填充数据--（先读后写）
            XSSFRow row = sheet.getRow(3);//获取第4行
            row.getCell(2).setCellValue(businessDataVO.getTurnover());//营业额
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());//有效订单数
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());//新增用户数
            row = sheet.getRow(4);//获取第5行
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());//有效订单数
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());//平均单价

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);//获取开始时间之后的每一天
                //查询某一天的营业数据
                BusinessDataVO businessData =
                        workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                //获取某一行
                row = sheet.getRow(7 + i);//读
                //获取单元格（先读后写）
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());

            }
            //写入到Excel中
            //3.通过输出流将Excel文件下载到客户端浏览器  不同于//通过输出流将内存中的Excel文件写入到磁盘"D:\\info.xlsx"
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
            in.close();//其实关闭资源应该写在finally中，以保证安全

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}


